﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace MengCC.Common.Serialize
{
    public class XmlConvert
    {
        /*
         * XmlSerializer 是提供xml序列化的类，我们把他封装得更加的简单
         */
        public static string SerializeObject(object value)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(value.GetType(), "");
            using (var strem = new MemoryStream())
            {
                xmlSerializer.Serialize(strem, value);
                strem.Position = 0;//在Serialize 方法写入后，数据量的下标已经不是 0了，所以要重新指定
                using (var reader = new StreamReader(strem, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }


        }

        public static T DeserializeObject<T>(string value)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (var strem = new MemoryStream())
            {
                using (var writer = new StreamWriter(strem, Encoding.UTF8))
                {
                    writer.Write(value);
                    writer.Flush();
                    strem.Position = 0;//Write 方法写入后，数据量的下标已经不是 0了，所以要重新指定
                    return (T)xmlSerializer.Deserialize(strem);
                }
            }
        }

        public static T DeserializeObject<T>(string value,Action<XmlSerializerNamespaces> namespaces)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (var strem = new MemoryStream())
            {
                using (var writer = new StreamWriter(strem, Encoding.UTF8))
                {
                    writer.Write(value);
                    writer.Flush();
                    strem.Position = 0;//Write 方法写入后，数据量的下标已经不是 0了，所以要重新指定
                    return (T)xmlSerializer.Deserialize(strem);
                }
            }
        }
    }
}
